package com.sjgtw.cloud.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.write.metadata.WriteSheet;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class EasyExcelUtil<T> {

    /**
     * 实体对象
     */
    public Class<T> clazz;

    public EasyExcelUtil(Class<T> clazz) {
        this.clazz = clazz;
    }

    public List<T> readExcel(MultipartFile file, Integer sheetNo, Integer headRowNumber){
        List<T> list = new ArrayList<>();

        AnalysisEventListener<T> analysisEventListener = new AnalysisEventListener<T>() {
            @Override
            public void invoke(T t, AnalysisContext analysisContext) {
                list.add(t);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {

            }
        };

        try {
            EasyExcel.read(file.getInputStream(), clazz, analysisEventListener).sheet(sheetNo).headRowNumber(headRowNumber).doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    public void exportExcel(HttpServletResponse response, List<T> list, String sheetName, String fileName, String templateName) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            final ClassPathResource classPathResource = new ClassPathResource("template/" + templateName);
            InputStream inputStream = classPathResource.getInputStream();

            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(inputStream).build();
            if (list != null) {
                addNum(list);
            } else {
                list = new ArrayList<>();
            }
            WriteSheet writeSheet1 = EasyExcel.writerSheet(sheetName).build();
            excelWriter.fill(list, writeSheet1);

            // 千万别忘记关闭流
            excelWriter.finish();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private <T> void addNum(List<T> list) {
        try {
            for (int i = 0; i < list.size(); i++) {
                T item = list.get(i);

                // 获取num字段，可能在父类中
                Field numField = ReflectionUtil.getField(item.getClass(), "num");
                numField.setAccessible(true);

                // 设置num字段的值
                numField.set(item, i + 1); // 这里假设num从1开始依次递增
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

}
